/*
Copyright (C) 2022 Matt Arnold
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
int main(int argc, char **argv)
{
    printf("%s", "\033[2J"); /* Clears the screen */
    printf("%s", "\033[H");
    long rate = 37;
    long slpt = 1;
    int opt;
    FILE *fp;
    bool havefile = false;
    char *fname;
    while ((opt = getopt(argc, argv, "r:t:f:")) != -1) {
        switch (opt) {
            case 'r':
                errno = 0;
                rate = strtol(optarg, NULL, 10);
                if (errno) {
                    fprintf(stderr, "%s\n", strerror(errno));
                    exit(1);
                }
                else {
                    rate /= 8;
                }
                break;
            case 't':
                errno = 0;
                slpt = strtol(optarg, NULL, 10);
                if (errno) {
                    fprintf(stderr, "%s\n", strerror(errno));
                    exit(1);
                }
                break;
            case 'f':
                 asprintf(&fname,"%s", optarg);
                havefile = true;
                break;





        }
    }

    int count = 0;
    char ch;
    if (havefile) {
        fp = fopen(fname, "r");
    }
    else { 
        fp = stdin;
    }

    while (!feof(fp)) { 
        if ( count == rate) {
            int isleep = (int) slpt;
            sleep(isleep);
            count = 0;
        }
        
        ch = getc(fp);
        putchar(ch);
        fflush(stdout);
        
        count++;
    }
    return 0;
}
